import React, { useState, useEffect, useRef } from 'react';
import { ProTable, PageContainer, ProForm, ProFormSelect, ProFormText, ProFormTreeSelect } from '@ant-design/pro-components';
import { Drawer, Button, message, Popconfirm } from 'antd';
import { deleteUser, fetchUserList, createUser, updateUser,resetPassword } from '@/services/ant-design-pro/user';
import { useModel } from '@umijs/max';

const UserList = () => {
  const [data, setData] = useState([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [loading, setLoading] = useState(false);
  const [form] = ProForm.useForm();
  const actionRef = useRef();
  const { dept,role } = useModel('roleModel');
  console.log(dept,'--dept')
  const loadData = async () => {
    setLoading(true);
    try {
      const response = await fetchUserList();
      if (response.code==='1') {
        setData(response.data);
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      console.error(error);
      message.error('获取用户数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (record) => {
    setCurrentRecord(record);
    form.setFieldsValue(record);
    setDrawerVisible(true);
  };

  const handleAdd = async () => {
    await setCurrentRecord(null);
    form.resetFields()
    setDrawerVisible(true);
   
  };

  const handleFinish = async (values) => {
    try {
      if (currentRecord) {
        // 编辑
        const response = await updateUser({ ...currentRecord, ...values });
        if (response.code === '1') {
          message.success('修改成功');
          actionRef.current?.reload();
        } else {
          message.error(response.msg);
        }
      } else {
        // 添加
        
        const response = await createUser(values);
        if (response.code === '1') {
          message.success('添加成功');
          actionRef.current?.reload();
          setDrawerVisible(false);
        } else {
          message.error(response.msg);
          return
        }
      }
    } catch (error) {
      message.error('操作失败');
    } 
  };

  const handleDelete = async (id) => {
    try {
      const response = await deleteUser({ id });
      if (response) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };
  const handleReset = async (record) => {
    try {
      const response = await resetPassword({ id: record.id });
      if (response) {
        message.success('重置成功');
        actionRef.current?.reload();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('重置失败');
    }
  };
  const columns = [
    {
      title: '姓名',
      dataIndex: 'userName',
      render: (text, record) => <a onClick={() => handleEdit(record)}>{text}</a>,
    }, {
      title: '用户名',
      dataIndex: 'loginId',
    },
    {
      title: '电子邮箱',
      dataIndex: 'email',
      search:false
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueEnum: {
        '1': { text: '男' },
        '2': { text: '女' },
      },
      search:false
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
        key="reload"
        title="确定重置密码么" onConfirm={() => {handleReset(record)}}>
        <a> 重置密码 </a>
        </Popconfirm>
        ,
        <a key="edit" onClick={() => handleEdit(record)}>
          编辑
        </a>,
          <Popconfirm
          key="delete"
          title="确定删除该项吗？"
          onConfirm={(event) => {
              event.stopPropagation();
              handleDelete(record.id)
          }}
          onCancel={(event) => {
              event.stopPropagation(); // 阻止事件冒泡
          }}
      >
        <a key="delete">
          删除
        </a>
        </Popconfirm>
      ],
    },
  ];

  return (
    <PageContainer header={{title:''}}>
      <ProTable
        columns={columns}
        rowKey="id"
        request={fetchUserList}
        loading={loading}
        search={{
          labelWidth: 'auto',
        }}
        actionRef={actionRef}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={handleAdd}>
            新增用户
          </Button>,
        ]}
      />
      <Drawer
        title={currentRecord ? '编辑用户' : '新增用户'}
        width={400}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <ProForm
          form={form}
          onFinish={handleFinish}
          initialValues={currentRecord || {}}
        >
          <ProFormText
            name="userName"
            label="姓名"
            placeholder="请输入用户姓名"
            rules={[{ required: true, message: '用户姓名不能为空' }]}
          />
          <ProFormText
            name="loginId"
            label="用户名"
            placeholder="请输入用户名"
            rules={[{ required: true, message: '用户名不能为空' }]}
          />
          <ProFormText
            name="email"
            label="电子邮箱"
            placeholder="请输入电子邮箱"
            rules={[{ type: 'email', message: '请输入有效的电子邮箱' }]}
          />
          <ProFormSelect
            name="sex"
            label="性别"
            options={[
              { label: '男', value: '1' },
              { label: '女', value: '2' },
            ]}
            placeholder="请选择性别"
            rules={[{ required: true, message: '请选择性别' }]}
          />
          <ProFormSelect
            name="rolesCode"
            label="角色"
            placeholder="请输入角色"
            request={async () => role}
            rules={[{ required: true, message: '角色不能为空' }]}
          />
          <ProFormTreeSelect
            key={'deptTree'}
            request ={()=>{ return dept}}
            fieldProps={{

              fieldNames: { label: 'name', value: 'id', children: 'treeList' }
            }}
            name="deptCode"
            label="部门"
            placeholder="请输入部门"
          />
          <ProFormText
            name="mobile"
            label="手机号码"
            placeholder="请输入手机号码"
            rules={[{ required: true, message: '手机号码不能为空', pattern: /^1[3-9]\d{9}$/,}]}
          />
        </ProForm>
      </Drawer>
    </PageContainer>
  );
};

export default UserList;
